import { _decorator, Component, EventTouch, Node, Prefab } from 'cc';
import { AudioConfig, GameConst, GameState, GGType } from './config/game-param';
import { Ground } from './Ground';
import { Bird } from './Bird';
import { EventManager } from './manager/event';
import { UICtrl } from './UICtrl';
import { AssetsManager } from './manager/assets-manager';
import { PipeCtrl } from './PipeCtrl';
import { AudioMgr } from './AudioMgr';
const { ccclass, property } = _decorator;

@ccclass('GameCtrl')
export class GameCtrl extends Component {

    @property({
        type: Ground,
        displayName: '地面控制器'
    })
    private ground: Ground

    @property({
        type: Bird,
        displayName: '小鸟控制器'
    })
    private bird: Bird

    @property({
        type: PipeCtrl,
        displayName: '管道控制器'
    })
    private pipe: PipeCtrl

    onLoad() {
        EventManager.on('on-collider', this.onMessageReceived, this)
        EventManager.on('on-touch-game-start', this.startGame, this)
        EventManager.on('on-touch-game-over', this.restartGame, this)

        // 加载bundle里的资源
        AssetsManager.instance.loadBundle('res-prefab').then(res => {
            this.initGame()
        })

        // 加载缓存里的记录
        GameConst.SELF_RECORD = Number(localStorage.getItem('self-record')) || 0
    }

    initGame() {
        const uiStart = AssetsManager.instance.getAsset('UIStart')
        UICtrl.instance.open(uiStart as Prefab)
    }

    restartGame() {
        // 鸟要先重置
        this.bird.resetPosition()
        this.pipe.resetGame()

        this.scheduleOnce(() => {
            this.startGame()
        }, 0.6)
    }

    startGame(event?: EventTouch) {
        GameConst.CURRENT_SCORE = 0
        this.ground.startMove()
        this.bird.startGame()
        this.pipe.startGame()

        const uiGame = AssetsManager.instance.getAsset('UIGame')
        UICtrl.instance.open(uiGame as Prefab)
    }

    gameOver(type: GGType) {
        this.ground.stopMove()
        this.bird.stopGame()
        this.pipe.stopGame()

        const uiOver = AssetsManager.instance.getAsset('UIOver')
        UICtrl.instance.open(uiOver as Prefab)

        UICtrl.instance.closed('UIGame')


        if (type === GGType.FailGround) AudioMgr.inst.playOneShot(AudioConfig.DIE)

        if (type === GGType.CollisionPipe) AudioMgr.inst.playOneShot(AudioConfig.HIT)
        
        this.setSelfRecord()
    }

    onMessageReceived(msg: GGType) {
        this.gameOver(msg)
    }

    setSelfRecord() {
        const currentSorce = Number(localStorage.getItem('self-record')) || 0
        if (GameConst.CURRENT_SCORE > currentSorce) localStorage.setItem('self-record', GameConst.CURRENT_SCORE.toString())
    }

    onDestroy() {
        EventManager.off('on-collider', this.onMessageReceived, this)
        EventManager.off('on-touch-game-start', this.startGame, this)
        EventManager.off('on-touch-game-over', this.startGame, this)
    }
}


